const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/** 计算倒计时的组成数组 */
function countTimes(value){
  // let value = computeTimes(end_time);
  let times = [];
  let day = parseInt(value / 60 / 60 / 24);
	let hourse = parseInt(value / 60 / 60) % 24;
	let minute = parseInt(value / 60) % 60;
  let second = parseInt(value % 60);
  times[0] = addZero(day);
  times[1] = addZero(hourse);
  times[2] = addZero(minute);
  times[3] = addZero(second);
  return times;
}

/**
 * 计算指定2个时间段的差数
 */
function computeTimes(end_time,start_time,flag){
  let startTime = null;
  if(start_time){//如果有开始时间，就取开始时间
    if(start_time.indexOf("-") != -1){
      start_time = start_time.replace(/-/g, '/');
    }
    startTime = parseInt(new Date(start_time).getTime() / 1000);
  }else{//如果没有开始时间，就取当前时间
    startTime = parseInt(new Date().getTime() / 1000);
  }
  //开播时间 (格式转化兼容ios)  
  if(end_time.indexOf("-") != -1){
    end_time = end_time.replace(/-/g, '/');
  }
  let endTime = parseInt(new Date(end_time).getTime() / 1000);
  if(flag){
    return parseInt(endTime - startTime);
  }
  return endTime <= startTime? 0 : parseInt(endTime - startTime);
}

/** 
 * 拆分时间
 * e[天，时，分，秒]
 * [10,12,12,12] => [[1,0],[1,2],[1,2],[1,2]]
 */
function splitDate(e){
  let list = JSON.parse(e)
  for (let i = 0; i< list.length; i++) {
    list[i] = list[i].toString.split('')
  }
  return list;
}

/** 数字补0 */
function addZero(num){
  return num<10 ? "0" + num : num;
}

/** 检测验证手机 */
function checkPhone (phone) {
  var re = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
  if (!(re.test(phone)) || phone == '') {
    return false
  } else {
    return true
  }
}

// 输出类似于 "f6763c23-aa64-495d-9e13-04c2dd232767" 的GUID值
function generateGuid() { 
  function S4() { 
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1); 
  } 
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); 
} 

 /**
 * 根据数组里的某个属性进行分组
 * @param {*} objArray  数组
 * @param {*} property  数组的某个属性
 */
function groupBy(objArray, property) {
  return objArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

module.exports = {
  formatTime,
  formatDate,
  countTimes,
  computeTimes,
  checkPhone,
  generateGuid
}
